﻿using Core.AdditionalInterfaces;
using Core.Logging;
using Core.Users;
using Infrastructure;
using Infrastructure.Managers;
using Newtonsoft.Json;
using RhotCMS.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RhotCMS.Controllers
{
    public class StoreController : RhotCMSController, IAllowPreview
    {
        public StoreController(ILogger logger, ICurrentUserService user)
            : base(logger, user)
        {
            _pageManager = new PageManager();
            _storeManager = new StoreManager();
        }

        public ActionResult Index()
        {  
            var page = _pageManager.GetSinglePageByGroupNameLang("Store", "Index", UILangName);

            if(page==null)
                return View("NotFound");

            var categories = _storeManager.GetCategoriesByParentId(UILangName);

            ViewBag.Categories = categories;

            return View(page);
        }

        public ActionResult Category(int id)
        {
            var products = _storeManager.GetProductsByCategoryId(UILangName, id);

            return View(products);
        }

        public string GetCart()
        {
            var cart = CartManager.GetCart();

            var result = JsonConvert.SerializeObject(cart, Formatting.Indented, new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                PreserveReferencesHandling = PreserveReferencesHandling.None
            });

            return result;
        }

        public string SetCart(Cart cart)
        {
            CartManager.SetCart(cart);
            return "OK";
        }

        public string AddToCart(int productId)
        {
            CartManager.AddToCart(productId, UILangName);
            return "OK";
        }
    }
}
